package demoMod.stsconsole.config;

import java.io.*;
import java.util.Properties;

public class SpireConfig {
    private final Properties properties;
    private String path;

    public SpireConfig(String path) {
        properties = new Properties();
        InputStream is = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            is = new FileInputStream(file);
            properties.load(is);
            this.path = path;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean hasKey(String key) {
        return properties.containsKey(key);
    }

    public int getInt(String key) {
        return Integer.parseInt(properties.getProperty(key));
    }

    public void setInt(String key, int value) {
        properties.setProperty(key, Integer.toString(value));
    }

    public float getFloat(String key) {
        return Float.parseFloat(properties.getProperty(key));
    }

    public void setFloat(String key, float value) {
        properties.setProperty(key, Float.toString(value));
    }

    public String getString(String key) {
        return properties.getProperty(key);
    }

    public void setString(String key, String value) {
        properties.setProperty(key, value);
    }

    public boolean getBoolean(String key) {
        return Boolean.parseBoolean(properties.getProperty(key));
    }

    public void setBoolean(String key, boolean value) {
        properties.setProperty(key, Boolean.toString(value));
    }

    public void save() {
        File file = new File(this.path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (OutputStream os = new FileOutputStream(file)) {
            properties.store(os, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
